package sessionbeans;

import java.util.Date;
import java.util.List;
import org.jboss.ejb3.annotation.RemoteBinding; 
import javax.ejb.Stateless;
import javax.persistence.*;

import entities.Ability;
import entities.HelpRequest;
import entities.RegisteredUser;

/**
 * Session Bean implementation class HelpRequestBean
 */
@Stateless
@RemoteBinding(jndiBinding="HelpRequestBeanRemote")
public class HelpRequestBean implements HelpRequestBeanRemote {

	private static final String GET_PENDING_REQUESTS = "select h from HelpRequest as h where h.receiver = :user and " +
			                                           "h.pending = true";
	private static final String anonymous = "anonymous";
	private static final String validEmail = ".+@.+[.][a-z]+";
	static final int MAX_CHARS = 255;
	@PersistenceContext
	private EntityManager manager;
	
    /**
     * Default constructor. 
     */
    public HelpRequestBean() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public List<HelpRequest> getPendingRequests(String userId) {
		RegisteredUser user = manager.find(RegisteredUser.class, userId);
		Query query = manager.createQuery(GET_PENDING_REQUESTS);
		query.setParameter("user", user);
		return (List<HelpRequest>)(query.getResultList());
	}

	@Override
	public void answerToHelpRequest(String requestId, boolean answer) {
		HelpRequest request = manager.find(HelpRequest.class, requestId);
		request.setPending(false);
		request.setAnswer(answer);
		manager.merge(request);
	}

	@Override
	public String sendHelpRequest(String sender, String receiver,
			String abilityName, String place, String description,
			double retribution) {
		RegisteredUser senderUser,receiverUser;
		Ability ability;
		Date date = new Date();
		String ok = "Help request sent correctly";
		String error = "Error in sending the help request";
		if(!fieldsAreCorrect(sender, receiver, abilityName, place, description, retribution)){
			return error;
		}
		senderUser = manager.find(RegisteredUser.class, sender);
		receiverUser = manager.find(RegisteredUser.class, receiver);
		ability = manager.find(Ability.class, abilityName);
		if ((senderUser != null || sender.matches(anonymous + validEmail)) && (receiverUser != null)) {
			HelpRequest newHelpRequest = new HelpRequest(senderUser,receiverUser,ability,date,place,description,retribution);
			if(sender.matches(anonymous + validEmail)){
				String eMail = sender.split(anonymous)[1];
				newHelpRequest.setEMail(eMail);
			}
			manager.persist(newHelpRequest);
			return ok;
		}
		return error;
	}
	
	private boolean fieldsAreCorrect(String sender, String receiver, String abilityName, String place,
			String description, double retribution){
		if(!description.isEmpty()){
			return !sender.isEmpty() && !receiver.isEmpty() && !abilityName.isEmpty() && !place.isEmpty() && 
					description.length() <= MAX_CHARS && retribution >= 0;
		}
		return false;
		
	}

}
